package com.w2e.common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class UploadUtils {

    // 方法获取文件的哈希值
    private static String getFileHash(File file) throws NoSuchAlgorithmException, IOException {
        MessageDigest digest = MessageDigest.getInstance("MD5");
        FileInputStream fis = new FileInputStream(file);
        byte[] byteArray = new byte[1024];
        int bytesCount = 0;

        while ((bytesCount = fis.read(byteArray)) != -1) {
            digest.update(byteArray, 0, bytesCount);
        }

        fis.close();

        byte[] bytes = digest.digest();
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }

        return sb.toString();
    }

    // 方法判断文件是否重复并返回已存在的文件名
    public static String isDuplicate(File file, String uploadDir) throws NoSuchAlgorithmException, IOException {
        String newFileHash = getFileHash(file);

        // 遍历上传目录中的所有文件，计算哈希值并比较
        File[] files = new File(uploadDir).listFiles();
        if (files != null) {
            for (File existingFile : files) {
                String existingFileHash = getFileHash(existingFile);
                if (newFileHash.equals(existingFileHash)) {
                    return existingFile.getName();
                }
            }
        }

        return null;
    }

}
